const { post } = require('../../utils/request');

Page({
  data: {
    type: '',
    duration: '',
    distance: '',
    calories: '',
    notes: ''
  },

  onLoad(options) {
    if (options.type) {
      this.setData({
        type: options.type
      });
    }
  },

  // 处理时长输入
  onDurationChange(e) {
    const duration = e.detail.value;
    this.setData({ duration });
    this.calculateCalories();
  },

  // 处理距离输入
  onDistanceChange(e) {
    const distance = e.detail.value;
    this.setData({ distance });
    this.calculateCalories();
  },

  // 处理热量输入
  onCaloriesChange(e) {
    const calories = e.detail.value;
    this.setData({ calories });
  },

  // 处理备注输入
  onNotesChange(e) {
    const notes = e.detail.value;
    this.setData({ notes });
  },

  // 计算消耗热量
  calculateCalories() {
    const { type, duration, distance } = this.data;
    let calories = 0;

    if (duration && distance) {
      // 根据不同运动类型计算大致热量消耗
      switch (type) {
        case '跑步':
          calories = distance * 60; // 每公里约60千卡
          break;
        case '步行':
          calories = distance * 30; // 每公里约30千卡
          break;
        case '骑行':
          calories = distance * 25; // 每公里约25千卡
          break;
        case '游泳':
          calories = duration * 8; // 每分钟约8千卡
          break;
        case '其他':
          calories = duration * 5; // 每分钟约5千卡
          break;
      }
    }

    this.setData({
      calories: calories.toFixed(2)
    });
  },

  // 表单提交
  async handleSubmit() {
    const { type, duration, distance, calories, notes } = this.data;

    // 表单验证
    if (!duration) {
      wx.showToast({
        title: '请输入运动时长',
        icon: 'none'
      });
      return;
    }

    if (!calories) {
      wx.showToast({
        title: '请输入消耗热量',
        icon: 'none'
      });
      return;
    }

    try {
      const data = {
        type,
        duration: parseInt(duration),
        distance: parseFloat(distance) || 0,
        calories: parseFloat(calories),
        notes,
        date: new Date().toISOString().split('T')[0]
      };

      await post('/records/sport', data);
      
      wx.showToast({
        title: '记录成功',
        icon: 'success'
      });

      // 返回上一页并刷新数据
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
    } catch (error) {
      wx.showToast({
        title: '记录失败',
        icon: 'none'
      });
    }
  }
}); 